package com.tastesport.chat.service;

import com.tastesport.chat.mapper.UserMapper;
import com.tastesport.chat.util.RedisUtil;
import org.jim.common.ImConst;
import org.jim.common.cache.redis.RedisCache;
import org.jim.common.packets.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class UserServiceImpl implements UserService {

    static AtomicInteger visitorid = new AtomicInteger(80000);

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisUtil redisUtil;
    @Value("${custom-attr.redis.rootname}")
    String redisRoot;

    RedisCache userCache = new RedisCache(ImConst.USER, -1, -1);

    @Override
    public User checkLogin(String userid) {
        User user = userCache.get(userid + ":" + ImConst.INFO, User.class);
        if (user != null) {
            user.setUserType(checkManager(userid));
            return user;
        } else {
            com.tastesport.chat.model.user.User u = userMapper.user(userid);
            User jimUser = new User();
            if (u == null) {
                String vId = "" + visitorid.addAndGet(1);
                jimUser.setId(vId);
                jimUser.setAccount(vId);
                jimUser.setNick("游客:" + visitorid.get());
                jimUser.setUserType(0);   // 用户类型  0:游客  1:会员  2:管理员
            } else {
                jimUser.setId(u.getId());
                jimUser.setAccount(u.getUsername());
                jimUser.setNick(u.getNickname());
                jimUser.setAvatar(u.getUserIcon());
                jimUser.setUserType(checkManager(userid));
//        jimUser.setTerminal("ws");
            }
            return jimUser;
        }
    }

    // 用户类型  0:游客  1:会员  2:管理员
    private Integer checkManager(String userId) {
        List managers = (List) redisUtil.lGet(redisRoot + ":manager", 0L, -1L);
        for (Object manager : managers) {
            if (userId.equals(manager)) {
                return 2;
            }
        }
        return 1;
    }

    /**
     * 从数据库中读取管理员列表并更新到redis缓存中
     *
     * @return
     */
    @Override
    public boolean initManager() {
        List<Object> list = redisUtil.lGet(redisRoot + ":manager", 0, -1);
        if (null != list && list.size() > 0) {
            return true;
        }
        List<String> userIds = userMapper.getManager();
        if (null != userIds && userIds.size() > 0) {
            redisUtil.del(redisRoot + ":manager");
            for (String id : userIds) {
                redisUtil.lSet(redisRoot + ":manager", id);
            }
            return true;
        } else {
            return false;
        }
    }

}
